package fr.insta.reverse.uml.webservice;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.insta.reverse.uml.bean.Projet;
import fr.insta.reverse.uml.controller.DefaultController;
import fr.insta.reverse.uml.service.ServiceFactory;
import fr.insta.reverse.uml.service.ServiceName;
import fr.insta.reverse.uml.service.ServiceProject;
import fr.insta.reverse.uml.util.InstaUtils;

public class GetImageUmlService extends DefaultController
{

	public GetImageUmlService(HttpServletRequest _request, HttpServletResponse _response)
	{
		super(_request, _response);
	}

	@Override
	public void execute() throws MalformedURLException
	{

		String scriptYuml = request.getParameter("scriptUml");
		String hash = request.getParameter("hash");

		if (request.getMethod() != "POST" || scriptYuml == null || hash == null)
			throw new MalformedURLException();

		scriptYuml = scriptYuml.replace("&lt;", "<");
		scriptYuml = scriptYuml.replace("&gt;", ">");
		scriptYuml = scriptYuml.replace("\t", "");
		scriptYuml = scriptYuml.replace("\n", "");

		try
		{
			scriptYuml = URLEncoder.encode(scriptYuml, "UTF-8");
		}
		catch (UnsupportedEncodingException e1)
		{
			e1.printStackTrace();
		}

		scriptYuml = scriptYuml.replace("%28", "(");
		scriptYuml = scriptYuml.replace("%29", ")");

		System.out.println("SCRIPT UML AFTER ENCODING : " + scriptYuml);

		try
		{
			String requestResponse = doPostRequest(scriptYuml);

			//The response have this state -> requestResponse : 9f07ef6d.png
			//We do not need the .png extension
			if (requestResponse.contains("."))
				requestResponse = requestResponse.substring(0, requestResponse.indexOf('.'));

			response.getWriter().write(requestResponse);

			//Insert the image in database if not empty
			if (hash != null && !hash.isEmpty() && !hash.contentEquals("null"))
			{
				System.out.println("hash :" + hash);

				ServiceProject serviceProjet = (ServiceProject) ServiceFactory.getService(ServiceName.ServiceProject);

				Projet project = serviceProjet.getByImageHash(hash);

				System.out.println(project);

				if (project != null)
				{
					serviceProjet.insertImageProject(request, project, requestResponse);
					response.getWriter().write(";" + project.getId());
				}
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * Do a POST request to the Yuml server to obtain the uml image generated
	 * @return
	 * @throws IOException 
	 */
	public String doPostRequest(String _scriptUml) throws IOException
	{
		String url = "http://yuml.me/diagram/scruffy;/class/";

		URL obj = new URL(url);

		Proxy proxy = InstaUtils.getProxyIfNeeded();

		HttpURLConnection con = (HttpURLConnection) obj.openConnection(proxy != null ? proxy : Proxy.NO_PROXY);

		con.setRequestMethod("POST");

		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

		// Send post request
		con.setDoOutput(true);
		con.setDoInput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());

		String postDatas = "dsl_text=" + _scriptUml;

		wr.writeBytes(postDatas);
		wr.flush();
		wr.close();

		int responseCode = con.getResponseCode();
		/*System.out.println("Sending 'POST' request to URL : " + url);
		System.out.println("Post parameters : " + "dsl_text=" + _scriptUml);
		System.out.println("Response Code : " + responseCode);*/

		InputStream inputStream = con.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

		String responseLine;
		StringBuilder responseBuilder = new StringBuilder();

		while ((responseLine = bufferedReader.readLine()) != null)
			responseBuilder.append(responseLine);

		bufferedReader.close();

		//print result
		System.out.println("Response from Yuml server : " + responseBuilder.toString());

		return responseBuilder.toString();
	}

}
